﻿using FarmSmartSleep.Common.Domain;
using FarmSmartSleep.Common.Domain.BeginTable;
using FarmSmartSleep.Common.Domain.PM;
using FarmSmartSleep.Common.Domain.RBACFile;
using FarmSmartSleep.Common.Domain.Sales_Purchase;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;

namespace FarmSmartSleep.Organ.API.Application.Sales_Purchase.BreedingSales
{
    /// <summary>
    /// 个体销售列表
    /// </summary>
    public class BreedingSalesListHandler:IRequestHandler<BreedingSalesListCommon, ResultPage<List<SalesRecordListDto>>>
    {
        private readonly IBaseRepository<SalesRecord> salesrecordRep;
        private readonly IBaseRepository<SleepInfor> sleepinforRep;
        private readonly IBaseRepository<Employee> employeeRep;
        private readonly IBaseRepository<DepartTree> treebaseRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="salesrecord"></param>
        /// <param name="sleepinfor"></param> 
        public BreedingSalesListHandler(IBaseRepository<SalesRecord> salesrecordRep, IBaseRepository<SleepInfor> sleepinforRep, IBaseRepository<Employee> employeeRep, IBaseRepository<DepartTree> treebaseRepository)
        {
            this.salesrecordRep = salesrecordRep;
            this.sleepinforRep = sleepinforRep; 
            this.employeeRep = employeeRep;
            this.treebaseRepository = treebaseRepository;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ResultPage<List<SalesRecordListDto>>> Handle(BreedingSalesListCommon request, CancellationToken cancellationToken)
        {
            //实例化消息体
            var result = new ResultPage<List<SalesRecordListDto>>() { Code = (int)CodeEnum.search };

            try
            {
                var treebase = treebaseRepository.GetAll();
                var salesrecord = salesrecordRep.GetAll().Where(x => x.Deletes == false);
                var sleepinfor = sleepinforRep.GetAll();
                var employee = employeeRep.GetAll();
                var listQuery = (from s in sleepinfor
                                 join m in salesrecord
                                 on s.SleepInforId equals m.EarTag
                                 join d in employee
                                 on m.CreateId equals d.EmployeeId
                                 join e in treebase 
                                 on m.Department equals e.DepartTreeId 
                                 group new { m,s,d,e} by m.SerialNumber into g
                                 select new SalesRecordListDto
                                 {
                                     SerialNumber = g.Key,
                                     TotalPrice = g.Sum(x=>x.m.Price),
                                     Count = g.Count(),
                                     SalesRecordId = g.First().m.SalesRecordId,
                                     SalesDate = g.First().m.SalesDate,
                                     Customer = g.First().m.Customer,
                                     SalesPerson = g.First().m.SalesPerson,
                                     Department = g.First().m.Department,
                                     DepartmentName = g.First().e.DepartTreeName,
                                     Warehouse = g.First().m.Warehouse,
                                     ShippingAddress = g.First().m.ShippingAddress,
                                     DocumentNumber = g.First().m.DocumentNumber, 
                                     EarTag = g.First().m.EarTag,
                                     EweName = g.First().s.EarNumber,
                                     Price = g.First().m.Price,
                                     ListPrice = g.First().m.ListPrice,
                                     DiscountRate = g.First().m.DiscountRate,
                                     Grade = g.First().m.Grade,
                                     Breed = g.First().m.Breed,
                                     Gender = g.First().s.Gender,
                                     SheepType = g.First().m.SheepType,
                                     BreedingStatus = g.First().m.BreedingStatus,
                                     Barn = g.First().m.Barn,
                                     Stall = g.First().m.Stall,
                                     BirthDate = g.First().s.SleepBirthDate,
                                     BirthWeight = g.First().s.SleepBirthWeight,
                                     WeaningWeight = g.First().m.WeaningWeight,
                                     FatherId = g.First().m.FatherId,
                                     MotherId = g.First().m.MotherId,
                                     AgeInMonths = g.First().m.AgeInMonths,
                                     Remarks = g.First().m.Remarks,
                                     CreateId = g.First().m.CreateId,
                                     CreateName = g.First().d.FirstName,
                                     CreateTime = g.First().m.CreateTime,
                                     UpdateId = g.First().m.UpdateId,
                                     UpdateName = g.First().d.FirstName,
                                     UpdateTime = g.First().m.UpdateTime,
                                     ExamId = g.First().m.ExamId,
                                     ExamName = g.First().d.FirstName,
                                     ExamTime = g.First().m.ExamTime,
                                 }).AsQueryable();
                if(request.salesDate != null)
                {
                    listQuery = listQuery.Where(x => x.SalesDate == request.salesDate);
                }
                
                if (!string.IsNullOrEmpty(request.DocumentNumber))
                {
                    listQuery = listQuery.Where(x => x.DocumentNumber.Contains(request.DocumentNumber));
                }
                if (!string.IsNullOrEmpty(request.Customer))
                {
                    listQuery = listQuery.Where(x => x.Customer.Contains(request.Customer));
                }
                if (!string.IsNullOrEmpty(request.ShippingAddress))
                {
                    listQuery = listQuery.Where(x => x.ShippingAddress.Contains(request.ShippingAddress));
                }
                if (!string.IsNullOrEmpty(request.SalesPerson))
                {
                    listQuery = listQuery.Where(x => x.SalesPerson.Contains(request.SalesPerson));
                }
                if (!string.IsNullOrEmpty(request.DocumentNumber))
                {
                    listQuery = listQuery.Where(x => x.DocumentNumber.Contains(request.DocumentNumber));
                }
                if (request.Department!=0)
                {
                    listQuery = listQuery.Where(x => x.Department == request.Department);
                }
                if (request.EarTag != 0)
                {
                    listQuery = listQuery.Where(x => x.EarTag == request.EarTag);
                }
                if (request.Department != 0)
                {
                    listQuery = listQuery.Where(x => x.Department == request.Department);
                }
                //仅在筛选后转换为列表
                var list = listQuery.ToList();
                result.totalCount = list.Count();
                result.totalPage = (int)Math.Ceiling(result.totalCount / (double)request.PageSize);
                list = list.OrderBy(c => c.SalesRecordId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                result.Code = (int)CodeEnum.success;
                result.Item = list;
                result.Messege = "查询成功";

            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
